package com.neusoft.bizcore.activiti.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.activiti.model.Process;
import com.neusoft.bizcore.activiti.model.QProcess;
import com.neusoft.bizcore.activiti.repository.CustomizedProcessRepository;
import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedProcessRepositoryImpl extends AbstractRepository
        implements CustomizedProcessRepository {

    @Override
    public List<Process> index(final Searchable searchable) {
        final QProcess qProcess = QProcess.process;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<com.neusoft.bizcore.activiti.model.Process> query =
                this.query().selectFrom(qProcess);
        query.where(where);
        return query.fetch();
    }

    @Override
    protected Class<?> getModelClass() {
        return Process.class;
    }

    @Override
    public Page<Process> search(final Pageable pageable, final Searchable searchable) {
        final QProcess qProcess = QProcess.process;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Process> query = this.query().selectFrom(qProcess);
        query.where(where);
        return super.search(query, pageable);
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QProcess qProcess = QProcess.process;

        if (!StringUtils.isEmpty(searchable.getStrValue("name"))) {
            where.and(super.containsStr(qProcess.name, searchable, "name"));
        }

        if (!StringUtils.isEmpty(searchable.getStrValue("code"))) {
            where.and(super.containsStr(qProcess.code, searchable, "code"));
        }

        final String[] roles = searchable.getStrArray("roles");
        if ((roles != null) && (roles.length > 0)) {
            where.and(super.inStrings(qProcess.roles.any().code, searchable, "roles"));
        }
        return where;
    }
}
